import java.io.*;
import java.util.*;

public class ProductService {
    private Map<String, Product> products = new HashMap<>();
    private String dataFile = "products.dat";

    // 构造函数中加载数据
    public ProductService() {
        loadData();
    }

    // 任务一：保存数据
    public void saveData() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(dataFile))) {
            oos.writeObject(products);
            System.out.println("数据已保存");
        } catch (IOException e) {
            System.out.println("保存失败: " + e.getMessage());
        }
    }

    // 任务一：加载数据
    @SuppressWarnings("unchecked")
    public void loadData() {
        File file = new File(dataFile);
        if (!file.exists()) return;

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(dataFile))) {
            products = (Map<String, Product>) ois.readObject();
            System.out.println("数据已加载");
        } catch (Exception e) {
            System.out.println("加载失败: " + e.getMessage());
        }
    }

    // 任务二：从配置文件加载路径
    public void loadConfig() {
        try (InputStreamReader reader = new InputStreamReader(new FileInputStream("config.properties"), "UTF-8")) {
            Properties props = new Properties();
            props.load(reader);
            dataFile = props.getProperty("data.file.path", "products.dat");
        } catch (IOException e) {
            System.out.println("配置文件加载失败，使用默认路径");
        }
    }

    // 任务三：备份数据
    public void backupData() {
        String backupFile = dataFile + ".bak";
        try (FileInputStream fis = new FileInputStream(dataFile);
             FileOutputStream fos = new FileOutputStream(backupFile)) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            System.out.println("备份完成: " + backupFile);

        } catch (IOException e) {
            System.out.println("备份失败: " + e.getMessage());
        }
    }

    // 商品管理方法
    public void addProduct(Product p) {
        products.put(p.getId(), p);
    }

    public Product getProduct(String id) {
        return products.get(id);
    }

    public void deleteProduct(String id) {
        products.remove(id);
    }

    public List<Product> getAllProducts() {
        return new ArrayList<>(products.values());
    }
}